import { useEffect, useState } from 'react'
import { List, Toast, NavBar, Icon } from 'antd-mobile'
import { reqCountryData } from '../../api/common'
import './index.less'
const Item = List.Item

export default function CountryPicker({ history, match }) {
  //国家代码
  let [countryData, setCountryData] = useState({})

  //组件挂载完成，请求所有国家代码
  useEffect(() => {
    async function getCountryData() {
      try {
        let res = await reqCountryData()
        setCountryData(res.data.data)
      } catch (err) {
        Toast.fail('请求失败,请刷新尝试...', 2)
      }
    }
    getCountryData()
  }, [])

  //返回
  const goBack = (value) => {
    return () => {
      switch (match.params.path) {
        case 'login':
          history.push('/login/code', value)
          break
        case 'register':
          history.push('/register/phone', value)
          break
        default:
          history.push('/')
          break
      }
    }
  }

  //侧边栏根据字母定位到相应国家代码区域
  const toCountry = (e) => {
    window.scrollTo(
      0,
      document.getElementById(e.target.textContent).offsetTop - 45
    )
  }

  //所有国家的键组成数组
  const countryKeys = Object.keys(countryData)

  return (
    <div>
      <NavBar
        mode="light"
        icon={<Icon type="left" className="icon-left" />}
        onLeftClick={() => history.goBack()}
        className="country-picker-navbar"
      >
        国家区号
      </NavBar>
      <div className="country-picker-list">
        {countryKeys.map((key) => (
          <List renderHeader={() => key} key={key} id={key}>
            {countryData[key].map((country) => {
              const countryKey = Object.keys(country)[0]
              const countryValue = '+' + country[countryKey]
              return (
                <Item
                  extra={countryValue}
                  key={countryKey}
                  className="country-picker-item"
                  onClick={goBack(countryValue)}
                >
                  {countryKey}
                </Item>
              )
            })}
          </List>
        ))}
      </div>
      <ul className="country-picker-sidebar" onClick={toCountry}>
        {countryKeys.map((key) => (
          <li key={key}>{key}</li>
        ))}
      </ul>
    </div>
  )
}
